package com.group3.controller.Validated;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.text.SimpleDateFormat;

import javax.validation.*;

/**
 * 日期格式验证,可以在{@code format}中添加有效的日期格式
 * @Author HY
 * @Description
 * @Date  2021/06/19
 * @return
 **/

@Documented
@Constraint(validatedBy = { DateValue.DateValueValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
public @interface DateValue {

    String message() default "日期格式不正确";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    /**
     * 有效的日期格式
     */
    String[] format() default {};

    /**
     * 
     * @Author HY
     * @Description
     * @Date  2021/06/19
     * @return 
     **/
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    @interface List {
        DateValue[] value();
    }


    public class DateValueValidator implements ConstraintValidator<DateValue, String> {

        private String[] formats;

        @Override
        public void initialize(DateValue constraintAnnotation) {
            formats = constraintAnnotation.format();
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {

            if(value==null || "".equals(value.trim())){return true;}
            if(formats.length==0){return true;}

            for (String string : formats) {
                try{
                    SimpleDateFormat formatter = new SimpleDateFormat(string);
                    formatter.parse(value);
                }catch(Exception e){
                    return false;
                }
            }
            return true;
        }

    }
}